package com.cook.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cook.dto.recipes.RecipesDTO;
import com.cook.entity.Recipes;
import com.cook.service.RecipesService;
import com.cook.mapper.RecipesMapper;
import com.cook.vo.recipes.RecipeDetailVO;
import com.cook.vo.recipes.RecipeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author black-white spider
* @description 针对表【recipes(食谱表)】的数据库操作Service实现
* @createDate 2025-10-27 19:55:23
*/
@Service
@Slf4j
public class RecipesServiceImpl extends ServiceImpl<RecipesMapper, Recipes> implements RecipesService {

    @Autowired
    private RecipesMapper recipesMapper;


    public Map<String, Object> getRecipesByUserIdWithPage(Long userId, Integer pageNum, Integer pageSize) {
        log.info("根据用户ID查询食谱列表： userId：{}，pageNum={}, pageSize={}", userId, pageNum, pageSize);

        if (userId == null || userId <= 0) {
            log.warn("用户ID参数不合法: {}", userId);
            throw new IllegalArgumentException("用户ID不能为空");
        }

        try {
            int offset = (pageNum - 1) * pageSize;
            //TODO
            List<RecipeVO> recipes = recipesMapper.selectByUserIdWithPage(userId, offset, pageSize);
            int totalCount = recipesMapper.selectRecipesCount();
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);

            Map<String, Object> result = new HashMap<>();
            result.put("list", recipes);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("totalCount", totalCount);
            result.put("totalPages", totalPages);
            result.put("hasNext", pageNum < totalPages);
            result.put("hasPrev", pageNum > 1);

            log.info("查询成功，共 {} 条食谱", recipes.size());
            return result;

        } catch (Exception e) {
            log.error("查询食谱列表失败: ", e);
            throw new RuntimeException("查询食谱列表失败");
        }
    }

    public RecipeDetailVO getRecipeById(Long recipeId) {
        log.info("根据ID查询食谱详情: {}", recipeId);

        if (recipeId == null || recipeId <= 0) {
            throw new IllegalArgumentException("食谱ID不能为空");
        }

        try {
            RecipeDetailVO recipe = recipesMapper.selectById(recipeId);
            if (recipe == null) {
                log.warn("食谱不存在: {}", recipeId);
                throw new RuntimeException("食谱不存在");
            }
            return recipe;
        } catch (Exception e) {
            log.error("查询食谱详情失败, recipeId: {}", recipeId, e);
            throw new RuntimeException("查询食谱详情失败");
        }
    }

    @Transactional
    public Long createRecipe(RecipesDTO recipesDTO) {
        log.info("创建食谱: {}", recipesDTO.getTitle());

        // 参数验证
        validateRecipeDTO(recipesDTO);

        try {
            // DTO 转 Entity
            Recipes recipe = new Recipes();
            BeanUtils.copyProperties(recipesDTO, recipe);

            // 插入数据库
            int result = recipesMapper.insertRecipe(recipe);
            if (result > 0) {
                log.info("食谱创建成功, ID: {}", recipe.getRecipeId());
                return recipe.getRecipeId();
            } else {
                throw new RuntimeException("创建食谱失败");
            }
        } catch (Exception e) {
            log.error("创建食谱失败: ", e);
            throw new RuntimeException("创建食谱失败");
        }
    }

    @Transactional
    public boolean updateRecipe(RecipesDTO recipesDTO) {
        log.info("更新食谱: {}", recipesDTO.getRecipeId());

        if (recipesDTO.getRecipeId() == null) {
            throw new IllegalArgumentException("食谱ID不能为空");
        }

        try {
            // DTO 转 Entity
            Recipes recipe = new Recipes();
            BeanUtils.copyProperties(recipesDTO, recipe);

            int result = recipesMapper.updateRecipe(recipe);
            boolean success = result > 0;
            if (success) {
                log.info("食谱更新成功: {}", recipesDTO.getRecipeId());
            } else {
                log.warn("食谱更新失败: {}", recipesDTO.getRecipeId());
            }
            return success;
        } catch (Exception e) {
            log.error("更新食谱失败: ", e);
            throw new RuntimeException("更新食谱失败");
        }
    }

    @Transactional
    public boolean deleteRecipe(Long recipeId, Long userId) {
        log.info("删除食谱: {}, 用户: {}", recipeId, userId);

        if (recipeId == null || userId == null) {
            throw new IllegalArgumentException("食谱ID和用户ID不能为空");
        }

        try {
            // 安全删除，确保用户只能删除自己的食谱
            int result = recipesMapper.deleteByIdAndUserId(recipeId, userId);
            boolean success = result > 0;
            if (success) {
                log.info("食谱删除成功: {}", recipeId);
            } else {
                log.warn("食谱删除失败或无权操作: {}", recipeId);
            }
            return success;
        } catch (Exception e) {
            log.error("删除食谱失败: ", e);
            throw new RuntimeException("删除食谱失败");
        }
    }

    /**
     * 分页查询所有食谱
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @return
     */
    public Map<String, Object> getAllRecipesWithPage(Integer pageNum, Integer pageSize) {
        log.info("分页查询所有食谱: pageNum={}, pageSize={}", pageNum, pageSize);

        try {
            int offset = (pageNum - 1) * pageSize;
            List<RecipeVO> recipes = recipesMapper.selectAllRecipesWithPage(offset, pageSize);
            int totalCount = recipesMapper.selectRecipesCount();
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);

            Map<String, Object> result = new HashMap<>();
            result.put("list", recipes);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("totalCount", totalCount);
            result.put("totalPages", totalPages);
            result.put("hasNext", pageNum < totalPages);
            result.put("hasPrev", pageNum > 1);

            log.info("查询成功，共 {} 条食谱", recipes.size());
            return result;

        } catch (Exception e) {
            log.error("查询食谱列表失败: ", e);
            throw new RuntimeException("查询食谱列表失败");
        }
    }

    /**
     * 查询食谱
     * @param title 标题关键词
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @return
     */
    public Map<String, Object> searchRecipesByTitle(String title, Integer pageNum, Integer pageSize) {
        log.info("根据标题搜索食谱: title={}, pageNum={}, pageSize={}", title, pageNum, pageSize);

        if (title == null || title.trim().isEmpty()) {
            log.warn("搜索关键词为空，返回所有食谱");
            return getAllRecipesWithPage(pageNum, pageSize);
        }

        try {
            int offset = (pageNum - 1) * pageSize;
            List<RecipeVO> recipes = recipesMapper.selectByTitleLike(title.trim(), offset, pageSize);
            int totalCount = recipesMapper.selectCountByTitleLike(title.trim());
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);

            Map<String, Object> result = new HashMap<>();
            result.put("list", recipes);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("totalCount", totalCount);
            result.put("totalPages", totalPages);
            result.put("keyword", title);
            result.put("hasNext", pageNum < totalPages);
            result.put("hasPrev", pageNum > 1);

            log.info("搜索成功，找到 {} 条相关食谱", recipes.size());
            return result;

        } catch (Exception e) {
            log.error("搜索食谱失败: title={}", title, e);
            throw new RuntimeException("搜索食谱失败");
        }
    }

    /**
     * 验证食谱DTO参数
     */
    private void validateRecipeDTO(RecipesDTO recipesDTO) {
        if (recipesDTO.getUserId() == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        if (recipesDTO.getTitle() == null || recipesDTO.getTitle().trim().isEmpty()) {
            throw new IllegalArgumentException("食谱标题不能为空");
        }
        if (recipesDTO.getTitle().length() > 100) {
            throw new IllegalArgumentException("食谱标题过长");
        }
    }
}





